from jmxquery import JMXConnection, JMXQuery
import os

# 1. 要开启JMX 2. 要能识别到Java

kafka_jmx = "172.16.100.74:9999"
MyJmxConnection = JMXConnection(f"service:jmx:rmi:///jndi/rmi://{kafka_jmx}/jmxrmi")

if os.path.exists('kafka_metric.tmp'):
    os.remove('kafka_metric.tmp')
# 获取全部指标写入到文件
jmx_query = [JMXQuery('*:*')]
metrics = MyJmxConnection.query(jmx_query)
for metric in metrics:
    with open(file='kafka_metric.tmp', mode='a+', encoding='utf-8') as f:
        f.write(f"{metric.to_query_string()} ({metric.value_type}) = {metric.value}"+'\n')

# 单独取出这些指标，生成json，topic的做成自发现
# https://blog.csdn.net/yangyijun1990/article/details/105129834